﻿
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using SCM.Domain;
using SCM.Domain.Ledger;
using SCM.Domain.StockCheck;
using SCM.Infrastructure.Interface;
using SqlSugar;
using System.Data;
using DbType = SqlSugar.DbType;

namespace SCM.Infrastructure.Implement
{
    public class DatabaseContext : IDatabaseContext, IDisposable
    {
        private readonly IConfiguration _configuration;

        private readonly string _connectionString;
        public SqlSugarScope SqlSugar {  get; }
        public IDbConnection DapperConnection { get; }

        public SqlSugarScope SqlSugarScope => throw new NotImplementedException();

        public DatabaseContext(IConfiguration configuration)
        {
           
            _connectionString = configuration.GetValue<string>("wmss");
            SqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = DbType.MySql,
                ConnectionString = _connectionString,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            },
            db =>
            {
                
                db.DbMaintenance.CreateDatabase("WMSRepository");
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);
                };
            });
            DapperConnection = new MySqlConnection(_connectionString);
        }

        public void Dispose()
        {
            DapperConnection?.Dispose();
            GC.SuppressFinalize(this);
        }
        public void InitializeDatabase()
        {
            try
            {
                // 初始化所有表
                SqlSugar.CodeFirst.InitTables(
                 // typeof(PurchaseRefundModel),
               //   typeof(PurchaseManagementModel),
                 // typeof(SaleManagementModel),
                 // typeof(SaleRefundModel),// 你的实体类
                 // typeof(StockModel),
                 // typeof(EnterOutModel),
                 // typeof(StockDistributeModel),
                //  typeof(GuaranteeModel)
               // typeof(WarnModel)
             // typeof(CheckModel)
             //typeof(ProfitLossModel)
                );

                Console.WriteLine("数据库表初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库初始化失败: {ex.Message}");
                throw; // 根据你的需求决定是否抛出异常
            }
        }
    }
}
